package com.zhongxi.guoyuan.widget.sliding;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.HashMap;
import java.util.Map;

/**
 * 自动适应高度的ViewPager
 *
 * @author kxx
 *         email codekxx@163.com
 */
public class CustomViewPager extends ViewPager {
    int lastX = -1;
    int lastY = -1;

    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int height = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height)
                height = h;
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int X = (int) ev.getRawX();
        int Y = (int) ev.getRawY();
        int dealX = 0;
        int dealY = 0;
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dealX = 0;
                dealY = 0;
                getParent().requestDisallowInterceptTouchEvent(true);  //不需要父View拦截子view的事件
                break;
            case MotionEvent.ACTION_MOVE:
                dealX += Math.abs(X - lastX);
                dealY += Math.abs(Y - lastY);
                if (dealX >= dealY) {
                    getParent().requestDisallowInterceptTouchEvent(true);   //左右滑动
                } else {
                    getParent().requestDisallowInterceptTouchEvent(false);  //上下滑动
                }
                lastX = X;
                lastY = Y;
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}
